'use strict';

var util = require('./util');

var directAlipay = require('direct-alipay');

var querystring = require('querystring');

var http = require('request');

var alipay = function(params) {
    params.precreate_url = 'https://openapi.alipay.com/gateway.do?';

    this.https_verify_url = 'https://mapi.alipay.com/gateway.do?service=notify_verify&';

    this.params = params;

    this.private_key = params.private_key;

    this.public_key = params.public_key;

    this._input_charset = 'utf-8';

    directAlipay.config(params);
}

alipay.prototype.buildDirectPayURL = function(orderParams) {
    return directAlipay.buildDirectPayURL(orderParams);
}

alipay.prototype.verity = function(params, callback) {
    return directAlipay.verity(params, callback);
}

alipay.prototype.buildWapPayUrl = function(orderParams) {

    var json = {
        service: 'alipay.wap.create.direct.pay.by.user', //alipay.wap.trade.create.direct
        payment_type: '1',
        _input_charset: this._input_charset,
        notify_url: this.params.notify_url,
        partner: this.params.partner,
        return_url: this.params.return_url,
        seller_id: this.params['seller_id'],
        key: this.params['key']
    };

    util.assignArray(json, orderParams);
    //加入签名结果与签名方式
    json.sign = util.buildSign(json, this);
    json.sign_type = 'MD5';

    var url = ['http://mapi.alipay.com/gateway.do?',
        querystring.stringify(json)
    ].join('');

    return url;
}

alipay.prototype.notify = function(params, callback) {
    directAlipay.verity(params, function(err, result) {

        if (err) {
            return callback(err);
        }

        var query_params = {
            partner: params.partner,
            notify_id: params.notify_id
        };

        var url = [
            this.https_verify_url,
            querystring.stringify(query_params)
        ].join('');

        http.get(url, function(err, reply) {

            if (err) {
                return callback(err);
            }

            reply = JSON.parse(reply);

            return callback(null, reply);
        });
    })
}

module.exports = alipay;
